package com.mingke.chat.message.logic;

import com.mingke.chat.config.RedisKeyEnum;
import com.mingke.chat.message.EasyChatMessage;
import com.mingke.chat.message.EasyChatMessageType;
import com.mingke.chat.message.request.EasyChatReportInfo;
import com.mingke.chat.message.response.CommonChatResponse;
import com.mingke.chat.message.response.EasyChatC2CResponse;
import com.mingke.chat.server.EasyChatClientChannelTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * @author mingke
 * @function TODO
 * @date 2021/12/20
 */
public class EasyChatReportInfoLogic implements EasyChatMessageLogic {
    //日志框架
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    //redis
    private RedisTemplate redisTemplate = null;
    /**
     * 执行前准备的方法
     */
    @Override
    public void prepare(EasyChatMessage message) {

    }

    /**
     * 数据存储的方法
     */
    @Override
    public void doStock(EasyChatMessage message) {

    }

    /**
     * 消息分发的方法
     */
    @Override
    public void dispatch(EasyChatMessage message) {

    }

    /**
     * 处理业务逻辑的方法
     *
     * @param message
     */
    @Override
    public void doLogic(EasyChatMessage message) {
        EasyChatReportInfo reportInfo = (EasyChatReportInfo) message;
        log.info("收到来自: "+reportInfo.getNumber()+"的上报，此用户已接入系统");
        //设置用户的登录状态
        redisTemplate.opsForHash().put(RedisKeyEnum.UserONLine.getKeyName(), reportInfo.getNumber().toString(), true);
        //检查如果用户存在离线消息的话，就在这个时候推送过去
        Long msgNum = redisTemplate.opsForList().size(reportInfo.getNumber().toString());
        if(msgNum > 0) {
            List<EasyChatC2CResponse> list = redisTemplate.opsForList().range(reportInfo.getNumber().toString(), 0, msgNum);
            //消费消息后，移除掉所有的消息
            redisTemplate.opsForList().trim(reportInfo.getNumber().toString(), 1, 0);
            Integer len = msgNum.intValue();
            CommonChatResponse chatResponse = new CommonChatResponse(len, EasyChatMessageType.C2CResponse.getMessageCode(), list.toArray(new EasyChatC2CResponse[len]));
            EasyChatClientChannelTool.instance.writeToClient(reportInfo.getNumber(), chatResponse);
        }
    }

    public EasyChatReportInfoLogic() {
        this.redisTemplate = (RedisTemplate) EasyChatLogicContext.instance.getContext().getBean("redisTemplate");
    }
}
